package com.example.noteshare;

import java.util.ArrayList;







import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.example.noteshare.Utilities.Constants;
import com.example.noteshare.Utilities.HTTP;
import com.example.noteshare.Utilities.Repo;
import com.example.noteshare.Utilities.RequestType;
import com.example.noteshare.asyncTasks.AsyncDownload;
import com.example.noteshare.gson.AccountCreationResult;
import com.example.noteshare.gson.ClassesResult;
import com.example.noteshare.gson.MyFile;
import com.example.noteshare.gson.MyFilesResult;
import com.example.noteshare.gson.Professor;
import com.example.noteshare.gson.ProfessorsResult;
import com.example.noteshare.gson.SearchResults;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;

public class SearchPage extends Activity implements OnClickListener {

	private Spinner spinClass, spinProf;
	
	private List<MyFile> files;
	
	String fileSelected;
	
	final Context context = this;
	
	
	ArrayAdapter<String> classAdapter, fileAdapter, profAdapter;
	
	public ArrayList<String> results = new ArrayList<String>();
	public ArrayList<String> classList = new ArrayList<String>();
	public ArrayList<String> profList = new ArrayList<String>();
	
	private ListView listView;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_search_page);
		
		this.files = new ArrayList<MyFile>();
		
		getActionBar().setTitle("Search Page");
	
		spinClass = (Spinner) findViewById(R.id.spinner_class);
		classAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, classList);
		classAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinClass.setAdapter(classAdapter);
		classAdapter.setNotifyOnChange(true);
		
		spinProf = (Spinner) findViewById(R.id.spinner_professor);
		profAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, profList);
		profAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinProf.setAdapter(profAdapter);
		profAdapter.setNotifyOnChange(true);
		
		listView = (ListView) findViewById(R.id.lstMyFiles);
		fileAdapter  = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, results);
		listView.setAdapter(fileAdapter);
		fileAdapter.setNotifyOnChange(true);
		
		String loginID = "1243";
		
		GetOptionsAsyncTask myTask = new GetOptionsAsyncTask();
		myTask.execute(loginID);
		
		
		Button btnSearch = (Button)this.findViewById(R.id.button_search);
		btnSearch.setOnClickListener(this);
		
		listView.setOnItemClickListener(new AdapterView.OnItemClickListener()
		{
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int pos, long id)
			{
				fileSelected =(String) parent.getItemAtPosition(pos); // name of file selected
				final MyFile fileId = files.get(pos);
		        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
		 
					// set title
					alertDialogBuilder.setTitle("Download");
		 
					// set dialog message
					alertDialogBuilder
						.setMessage("Download Notes from NoteShare?")
						.setCancelable(false)
						.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,int id) {
								Map<String, String> params = new HashMap<String, String>();
								params.put("userId", Repo.userId);
								params.put("fileId", fileId.getId());
								AsyncDownload async = new AsyncDownload(Constants.serverIP + Constants.getFile, params, "mnt/sdcard/", getApplicationContext());
								async.execute();
							}
						})
						.setNegativeButton("Cancel",new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,int id) {
								// if this button is clicked, just close
								// the dialog box and do nothing
								dialog.cancel();
							}
						});
		 
						// create alert dialog
						AlertDialog alertDialog = alertDialogBuilder.create();
		 
						// show it
						alertDialog.show();

			}
		});
		
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.search_page, menu);
		return true;
	}
	
	public void onClick(View v){
        switch(v.getId()){
        case R.id.button_search:
        	
        	String loginID = "1243";
        	
        	EditText txtSearch = (EditText)this.findViewById(R.id.edit_search);
    
        	
        	String name = txtSearch.getText().toString(); 
      
        	spinClass = (Spinner) findViewById(R.id.spinner_class);
        	spinProf = (Spinner) findViewById(R.id.spinner_professor);
        	
        	String course = String.valueOf(spinClass.getSelectedItem());
        	String prof = String.valueOf(spinProf.getSelectedItem());
        	
        	SearchAsyncTask searchTask = new SearchAsyncTask();
			searchTask.execute(loginID, course, prof, name);
		
        break;
      
        }
	}
	
	public class GetOptionsAsyncTask extends AsyncTask<String, Void, Void> {	
		
		ArrayList<String> classes;
		ArrayList<String> profs;
		
		
		@Override
		protected void onPostExecute(Void arg0) {
			classAdapter.clear();
			classAdapter.addAll(classes);
			classAdapter.notifyDataSetChanged();
			
			profAdapter.clear();
			profAdapter.addAll(profs);
			profAdapter.notifyDataSetChanged();
		}
	
		@Override
		protected Void doInBackground(String... params) {
			
			String loginID=  params[0];
			
			String output = "";
			try {				
				classes = classApp(loginID);
				profs = profApp(loginID);				
			} catch (Exception e) {
				
			}
			
			return null;			
		}
	}
	
	
	
	public class SearchAsyncTask extends AsyncTask<String, Void, Void> {	
		
		ArrayList<String> result;

		@Override
		protected void onPostExecute(Void arg0) {
			fileAdapter.clear();
			fileAdapter.addAll(result);
			fileAdapter.notifyDataSetChanged();

		}
	
		@Override
		protected Void doInBackground(String... params) {
			
			String loginID =  params[0];
			String course =  params[1];
			String professor =  params[2];
			String name =  params[3];
			
			try {
				result = searchApp(loginID, course, professor, name);	
			} catch (Exception e) {
				
			}

			return null;			
		}
	}
	

	private ArrayList<String> classApp(String loginID) throws Exception{
		
		Map<String, String> params = new HashMap<String, String>();
		String result = HTTP.doRequest(RequestType.GET, Constants.serverIP + Constants.getClasses, params);
		
		//parse tje results
		Gson gson = new GsonBuilder().create();
		ClassesResult cr = gson.fromJson(result, ClassesResult.class);
		
		ArrayList<String> results = new ArrayList<String>();
		
		for(com.example.noteshare.gson.Class c : cr.getClasses()){
			results.add(c.getCourse());
		}
		results.add("None");
		
		return results;
		
	}
	
	private ArrayList<String> profApp(String loginID) throws Exception{
		
		Map<String, String> params = new HashMap<String, String>();
		String result = HTTP.doRequest(RequestType.GET, Constants.serverIP + Constants.getProfessors, params);
		
		//parse tje results
		Gson gson = new GsonBuilder().create();
		ProfessorsResult cr = gson.fromJson(result, ProfessorsResult.class);
		
		ArrayList<String> results = new ArrayList<String>();
		
		for(Professor p : cr.getProfessors()){
			results.add(p.getProfessor());
		}
		results.add("None");
      
		return results;
		
	}

	private ArrayList<String> searchApp(String loginID, String course, String professor, String name) throws Exception{
		
		this.files.clear();
		
		Map<String, String> params = new HashMap<String, String>();
		params.put("class", course);
		params.put("professor", professor);
		params.put("fileName", name);
		
		
		String result = HTTP.doRequest(RequestType.GET, Constants.serverIP + Constants.search, params);
		//parse tje results
		Gson gson = new GsonBuilder().create();
		SearchResults cr = gson.fromJson(result, SearchResults.class);
		
		ArrayList<String> results = new ArrayList<String>();
		
		for(MyFile f : cr.getResults()){
			files.add(f);
			results.add(f.getName());
		}
      
		return results;
		
	}
}
